// imageTools.cpp
//
// Tools for writing generic and specific image processing functions

#include "image/imageTools.h"
namespace simple{

    //
    // Image Intersection Routines
    //
    IntersectRects intersect (const Rect& src, const Rect& dst)
    {
        IntersectRects overlap;
        Rect srcOverlap = src;
        if (!dst.isNull())
            srcOverlap = srcOverlap.intersect (dst);

        overlap.src = srcOverlap;
        overlap.dst = srcOverlap;
        return overlap;
    }


    IntersectRects intersect (const Rect& src, unsigned int xKernelSize, unsigned int yKernelSize, const Rect& dst)
    {
        IntersectRects overlap;
        if (xKernelSize < 1 || yKernelSize < 1)
            return overlap;

        // Expand the dst region to indicate pixels we would "like"
        // to have in our image.
        int xExpansion = (xKernelSize-1) / 2;
        int yExpansion = (yKernelSize-1) / 2;
        Rect dstRegion = dst;
        dstRegion.expand (xExpansion, yExpansion);

        // The source pixels we'll use are just the intersection
        Rect srcRegion = src;
        srcRegion = srcRegion.intersect (dstRegion);

        // We're done if there is no overlap or the overlap
        // area is not big enough.
        if (srcRegion.isNull() || 
            srcRegion.width() < xKernelSize || srcRegion.height() < yKernelSize)
            return overlap;

        // The destination pixels we'll have are handled by 
        // shrinking (i.e. eroding) the source region
        dstRegion = srcRegion;
        dstRegion.expand (-xExpansion, -yExpansion);

        overlap.src = srcRegion;
        overlap.dst = dstRegion;
        return overlap;
    }


    IntersectRects intersect (const Rect& src1, const Rect& src2, const Rect& dst)
    {
        IntersectRects overlap;

        // Setup our src and dst regions we have to work with
        Rect srcOverlap = src1;
        srcOverlap = srcOverlap.intersect (src2);
        if (!dst.isNull())
            srcOverlap = srcOverlap.intersect (dst);

        overlap.src = srcOverlap;
        overlap.dst = srcOverlap;
        return overlap;
    }

}